package cn.acewill.yxd.yunxundian.pubClass;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;

public class signuppanel extends Activity {
    protected static YXDAPP yxdapp=new YXDAPP();
    protected static DbManager db = x.getDb(yxdapp.getDaoConfig());
    private ImageView img;
    private Bitmap mBitmap;
    private Canvas canvas;
    private Paint paint;
    // 重置按钮
    private Button reset_btn;
    private Button save_btn;
    private Button sureBtn;
    private View backBtn;
    public String retUrl="0";
    private int schid;
    private int cmdid=-1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signuppanel);
        schid= getIntent().getIntExtra("rrschid",-1);
        backBtn=(View)findViewById(R.id.btBack);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        img = (ImageView) findViewById(R.id.iv);
        save_btn=(Button)findViewById(R.id.btSave);
        save_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveImg();
            }
        });
        reset_btn = (Button) findViewById(R.id.btReset);
        reset_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                img.setImageBitmap(null);
                showImage();
            }
        });
        // 绘图
        try {
            getSignatureBitmap();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void showImage() {
        // 创建一张空白图片
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        double bmpheight=dm.heightPixels*0.8;

        mBitmap = Bitmap.createBitmap(dm.widthPixels,(int)bmpheight, Bitmap.Config.ARGB_8888);
        // 创建一张画布
        canvas = new Canvas(mBitmap);
        // 画布背景为白色
        canvas.drawColor(Color.WHITE);
        // 创建画笔
        paint = new Paint();
        // 画笔颜色为蓝色
        paint.setColor(Color.BLACK);
        // 宽度5个像素
        paint.setStrokeWidth(5);
        // 先将白色背景画上
        canvas.drawBitmap(mBitmap, new Matrix(), paint);
        img.setImageBitmap(mBitmap);

        img.setOnTouchListener(new View.OnTouchListener() {
            int startX;
            int startY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 获取手按下时的坐标
                        startX = (int) event.getX();
                        startY = (int) event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 获取手移动后的坐标
                        int endX = (int) event.getX();
                        int endY = (int) event.getY();
                        // 在开始和结束坐标间画一条线
                        canvas.drawLine(startX, startY, endX, endY, paint);
                        // 刷新开始坐标
                        startX = (int) event.getX();
                        startY = (int) event.getY();
                        img.setImageBitmap(mBitmap);
                        break;
                }
                return true;
            }
        });

    }

    public void saveImg() {
        try {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
            Random random =new Random();
            //100以内的随机数
            String newPhotoName="yxd_signature"+random.nextInt(100)+""+sdf.format(new Date());
            String thisUrl=getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/"+newPhotoName+".jpg";
            retUrl=thisUrl;
            File file = new File(thisUrl);
            FileOutputStream stream = new FileOutputStream(file);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            stream.close();

            //模拟一个消息通知系统sd卡被重新挂载了
//            Intent intent = new Intent();
//            intent.setAction(intent.ACTION_MEDIA_MOUNTED);
//            retUrl=Uri.fromFile(Environment
//                    .getExternalStorageDirectory()).toString();
//            intent.setData(Uri.fromFile(Environment
//                    .getExternalStorageDirectory()));
//            sendBroadcast(intent);

            CommonMapBean cmb=new CommonMapBean();
            if (cmdid>-1){
                cmb.set_ID(cmdid);
            }
            cmb.setCmValue(retUrl);
            cmb.setCmType("门店签名");
            cmb.setIndexNum(schid+"");
            db.saveOrUpdate(cmb);
            Toast.makeText(this, "保存图片成功", Toast.LENGTH_SHORT).show();
            finish();
//            Intent in = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putString("returl", retUrl);
//            bundle.putInt("schid",schid);
//            in.putExtras(bundle);
//            this.setResult(100, in);
//            finish();

        } catch (Exception e) {
            Toast.makeText(this, "保存图片失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }

    public void getSignatureBitmap() throws DbException {
        CommonMapBean cmb = db.selector(CommonMapBean.class).where("CmType", "=", "门店签名")
                .and("IndexNum", "=", schid + "")
                .findFirst();
        if (cmb != null) {
            if (!cmb.getCmValue().toString().equals("")) {
                cmdid = cmb.get_ID();
                File f = new File(cmb.getCmValue().toString());
                Glide.with(signuppanel.this).load(f).into(img);
            }
        }else{
            showImage();
        }

    }

}
